<?php


namespace app\lmsx\admin;

use app\common\builder\ZBuilder;
use app\lmsx\model\Code as CodeModel;
use think\Db;

/**
 * 资料库
 * @author lan
 */
class Code extends Base
{
    public function index(){
        // 获取查询和排序规则
        $map = $this->getMap();
        $order = $this->getOrder();
        // 批量指定识别码按钮
        $btn = [
            'title' => '生成识别码',
            'icon'  => 'fa fa-fw fa-hand-pointer-o',
            'class' => 'btn btn-primary ajax-get',
            'href'  => url('recode')
        ];
        $btn_access = [
            'title' => '取消指派识别码',
            'icon'  => 'fa fa-fw fa-share',
            'class' => 'btn btn-xs btn-default ajax-get',
            'href'  => url('download_img', ['id' => '__id__'])
        ];
        $data = Db::view('lmsx_code')
            ->view('lmsx_user','nickname','lmsx_user.id=lmsx_code.user_id','left')
            ->where($map)
            ->order($order)
            ->order('lmsx_code.id desc')
            ->paginate()->each(function($item){
                // 对分页数据可以做额外处理
                $item['img'] = 'https://jiaoyu.mogochina.com/public/'.$item['xcx_code'].'.jpg';
                return $item;
            });
        return ZBuilder::make('table')
            ->setTableName('lmsx_code')  //需要修改 这里修改正确可以直接修改字段 删除
            ->addColumns([
                ['id','id'],
                ['code','识别码'],
                ['xcx_code','小程序码'],
                ['nickname','识别码指定用户'],
                ['img','小程序码图片','img_url',''],
                ['create_time','创建时间','datetime'],
                ['right_button', '操作', 'btn']
            ])
//            ->addTopButton('add', [],[])
            ->addRightButton('edit',['title' => '指派识别码','icon'  => 'fa fa-fw fa-hand-pointer-o'],[])
            ->addRightButton('download_img', $btn_access) // 添加授权按钮
            ->addTopButtons(['delete'])
            ->setRowList($data)
             ->addTopButton('recode',$btn)
            ->addFilter(['nickname'=>'lmsx_user'])
            ->setSearch(['id' => 'ID', 'code' => '识别码'])
            ->fetch();
    }
//    public function add(){
//        if($this->request->isPost()){
//            // 第一步 获取数据 如果后台面向大众 需要用only方法
//            $data = request()->post();
//            // 第二部 验证数据
//            $result = $this->validate($data,'Banner');
//            if($result!==true) $this->error($result);
//            //dump($data);die;
//            // 第三部 存储
//            BannerModel::create($data);
//            $this->success('保存成功', null, '_parent_reload');
//        }
//
//        return ZBuilder::make('form')
//            ->addFormItems([
//                ['image','img','广告图片','必须，图片大小限2M'],
//                ['radio','category','广告图分类','必须,单选',$this->arr],
//                ['number','sort','排序','',0],
//                ['radio','status','是否显示','',['否','是'],1],
//            ])
//            ->fetch();
//    }


    public function edit($id=null){
        if($this->request->isPost()){
            $data = request()->post();
            $result = $this->validate($data,'Code');
            if($result!==true) $this->error($result);
            CodeModel::update($data);
            $this->success('保存成功', null, '_parent_reload');
        }

//        $data = DatumModel::get($id);
        $data=Db::table('dp_lmsx_code')->where('id',$id)->find();
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['select','user_id','用户','必须，单选',(new CodeModel())->getAllUser()],
            ])
            ->setFormData($data)
            ->fetch();
    }

    //生成识别码
    public function recode(){
        $data=[];
        $data['code']=(new CodeModel())->createCode();
        //return json($data);
        $data['xcx_code']='lm'.$data['code'];
        $row=CodeModel::create($data);
        //生成小程序码
        $appid=config('weiXin')['appid'];
        $secret=config('weiXin')['secret'];
        $url1="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $access_token = json_decode(get_curl($url1), true)['access_token'];
        $page="pages/index/index";
//        $scene = 'xcx_code='.$row['xcx_code'];
        $scene =$row['xcx_code'];
        $width=430;
        $post_data='{"scene":"'.$scene.'","page":"'.$page.'","width":'.$width.'}';
        $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
        $result=api_notice_increment($url,$post_data);
        if(!file_exists($row['xcx_code'].'.jpg')){
            file_put_contents($row['xcx_code'].'.jpg', $result);
        }
        $this->success('生成识别码成功', null, '_parent_reload');

    }

    //下载小程序码图片
    public function download_img($id)
    {
        if(empty($id))$this->error('参数错误');
        $row=Db::table('dp_lmsx_code')->find($id);
        if($row['user_id']==0) $this->error('已取消');
        Db::table('dp_lmsx_code')->where('id',$id)->update(['user_id'=>0]);
        $this->success('取消成功', null, '_parent_reload');
    }
}